#include <bits/stdc++.h>
// N^2算法。。。
using namespace std;

int n;
vector<int> a;
vector<vector<int>> sons;
vector<unordered_map<int, long long>> dp;

long long calCost(int x, int y)
{
    if (x == 0 || y == 0)
        return 0;
    return abs(a[x] - a[y]);
}

long long dfs(int curr, int mNext = 0)
{
    auto &cSons = sons[curr];
    if (cSons.size() == 0)
    {
        dp[curr][curr] = 0;
        return 0 + calCost(curr, mNext);
    }
    else if (cSons.size() == 1)
    {
        int u = cSons[0];
        long long minUCost = dfs(u, mNext), cuCost = calCost(curr, u);
        for (auto pu : dp[u])
        {
            int x = pu.first;
            long long cost = pu.second;
            dp[curr][x] = cost + cuCost;
        }
        unordered_map<int, long long>().swap(dp[u]);
        return cuCost + minUCost;
    }
    else if (cSons.size() == 2)
    {
        int u = cSons[0], v = cSons[1];
        long long minUCost = dfs(u, v);
        long long minVCost = dfs(v, u);

        long long min_u_to_v = minUCost;
        // for (auto const &pu : dp[u])
        // {
        //     int ux = pu.first;
        //     long long uCost = pu.second;
        //     min_u_to_v = min(min_u_to_v, uCost + calCost(ux, v));
        // }

        long long min_v_to_u = minVCost;
        // for (auto const &pv : dp[v])
        // {
        //     int vx = pv.first;
        //     long long vCost = pv.second;
        //     min_v_to_u = min(min_v_to_u, vCost + calCost(vx, u));
        // }

        long long cost_u_first = calCost(curr, u) + min_u_to_v;
        long long cost_v_first = calCost(curr, v) + min_v_to_u;

        long long mini = INT64_MAX;

        for (auto const &pu : dp[u])
        {
            // v子树在前，u子树在后。最终的叶子节点来自u子树
            int ux = pu.first;
            long long uCost = pu.second;
            dp[curr][ux] = cost_v_first + uCost;
            mini = min(mini, dp[curr][ux] + calCost(ux, mNext));
        }
        unordered_map<int, long long>().swap(dp[u]);
        for (auto const &pv : dp[v])
        {
            // u子树在前，v子树在后。最终的叶子节点来自v子树
            int vx = pv.first;
            long long vCost = pv.second;
            dp[curr][vx] = cost_u_first + vCost;
            mini = min(mini, dp[curr][vx] + calCost(vx, mNext));
        }
        unordered_map<int, long long>().swap(dp[v]);
        return mini;
    }
    else
    {
        assert(false);
    }
}

int main()
{
    cin >> n;
    a.resize(n + 1);
    sons.resize(n + 1);
    dp.resize(n + 1);
    for (int i = 1; i <= n; ++i)
    {
        int x;
        cin >> x;
        a[i] = x;
    }
    for (int i = 2; i <= n; ++i)
    {
        int f;
        cin >> f;
        sons[f].push_back(i);
    }
    cout << dfs(1) << endl;
    // system("pause");
    return 0;
}
